import React, { useMemo } from 'react';
import { connect } from 'umi';
import { Tabs } from 'antd';
import MenuOperationDOM from '@/components/menuOption';
import { MenuOutlined } from '@ant-design/icons';
import { tabsMenuOperation } from '@/utils/option/layouts';
import loadable from '@loadable/component';
import BaseOther from './baseOther';

const LayoutIframeDom = loadable(() => import('./iframeDom'), {});
const { TabPane } = Tabs;

const LayouHanderDOM = (props) => {
  const { dispatch, tabsArr, activeKey } = props;

  // 标签页操作事件
  const tabOnChange = async (key) => {
    // 激活当前 tab
    await dispatch({ type: 'layoutApi/setTabsActiveKey', payload: key });
    // 更新 iframe 的 url
    await dispatch({ type: 'layoutApi/setIframeUrl', target: key });
    // 更新展开菜单的keys[] 通过便签栏中已有的菜单定位左侧的菜单
    await dispatch({ type: 'layoutApi/setLeftShowMenuKeys', payload: key });
  };

  // 操作标签
  const onEditOperation = (targetKey, action) => {
    // 移除标签
    if (action === 'remove') {
      tabsOperation(tabsArr.filter((f) => f?.key != targetKey));
      // 如果移除激活标签则返回首页
      if (targetKey == activeKey) {
        tabOnChange(tabsArr[0].key);
      }
    }
  };

  // 标签栏右侧 - 操作栏事件
  const handleMenuClick = async (target) => {
    await dispatch({ type: 'layoutApi/closeTabs', target: target.key });
  };

  // 标签栏公用方法
  const tabsOperation = async (data = []) => {
    // 更新头部标签栏集合
    await dispatch({ type: 'layoutApi/setPushHeaderTabs', payload: data });
    // 更新头部标签栏当前激活key
    await dispatch({ type: 'layoutApi/setTabsActiveKey', payload: data[data.length - 1].key });
    // 更新展开菜单集合
    await dispatch({
      type: 'layoutApi/setOpenKeys',
      payload: data[data.length - 1]?.pro_layout_parentKeys,
    });
    // 激活剩余菜单
    await dispatch({ type: 'layoutApi/setMenuSelectKeys', payload: [data[data.length - 1].key] });
  };

  // 渲染tab右侧操作部分
  const renderRightOperation = useMemo(() => {
    return {
      right: (
        <MenuOperationDOM
          trigger="click"
          content={<MenuOutlined />}
          data={tabsMenuOperation}
          onMenuChange={handleMenuClick}
        />
      ),
    };
  }, []);

  // 渲染基本信息组件
  const renderComponents = (record) => {
    if (!!record.url) {
      return <LayoutIframeDom menuKey={record.key} iframeUrl={record.url} />;
    } else {
      return <BaseOther target={record.component || ''} />;
    }
  };

  return (
    <Tabs
      className="tabs-record"
      hideAdd
      size="small"
      type="editable-card"
      onChange={tabOnChange}
      onEdit={onEditOperation}
      tabBarExtraContent={renderRightOperation}
      activeKey={activeKey}
    >
      {tabsArr.map((t) => (
        <TabPane tab={t.name} key={t.key} {...t}>
          {renderComponents(t)}
        </TabPane>
      ))}
    </Tabs>
  );
};

export default connect(({ layoutApi }) => ({
  tabsArr: layoutApi.tabsArr,
  activeKey: layoutApi.activeKey,
}))(LayouHanderDOM);
